package com.beetlestech.nfe.main.biz.com.util;

import java.io.ByteArrayInputStream;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.beetlestech.nfe.fw.core.bean.BeanFactory;
import com.beetlestech.nfe.fw.core.biz.AbstractComponent;
import com.beetlestech.nfe.fw.core.config.SystemContext;
import com.beetlestech.nfe.fw.core.properties.MessageProperties;
import com.beetlestech.nfe.main.biz.constant.CommonConfigConstant;
import com.google.gson.Gson;

public class JsonSmsClient extends AbstractComponent implements CommonConfigConstant{

	private static volatile JsonSmsClient conf;

	private String accountSid = null;
	
	private String authToken = null;
	
	private String appId = null;
	
	private String templateId = null;
	
	private String server = null;
	
	private String version = null;
	
	private JsonSmsClient() {
		try {
			BeanFactory beanFactory = SystemContext.getBeanFactory();
			MessageProperties resourcesProperties = beanFactory.beanOfName(COMMON_CONFIG_FILENAME);
			accountSid = resourcesProperties.get(REST_ACCOUNTSID);
			authToken = resourcesProperties.get(REST_TOKEN);
			appId = resourcesProperties.get(REST_APPID);
			templateId = resourcesProperties.get(REST_TEMPLATEID);
			server = resourcesProperties.get(REST_SERVER);
			version = resourcesProperties.get(REST_VERSION);
		} catch (Exception e) {
			e.printStackTrace();
			createApplicationException("M10440WS", "SMS设定数据");
		}
	}
	
	public static JsonSmsClient getInstance() {
		if (conf == null) {
			synchronized (JsonSmsClient.class) {
				if (conf == null) {
					conf = new JsonSmsClient();
				}
			}
		}
		return conf;
	}
	
	public String templateSMS(String to, String param) {

		String result = "";
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			//MD5加密
			EncryptUtil encryptUtil = new EncryptUtil();
			
			// 构造请求URL内容
			String timestamp = CustomDateUtil.dateToStr(new Date(),
					CustomDateUtil.DATE_TIME_NO_SLASH);// 时间戳
			
			String signature = getSignature(timestamp, encryptUtil);
			
			String url = getStringBuffer().append("/").append(version)
					.append("/Accounts/").append(accountSid)
					.append("/Messages/templateSMS")
					.append("?sig=").append(signature).toString();
			
			TemplateSMS templateSMS=new TemplateSMS();
			templateSMS.setAppId(appId);
			templateSMS.setTemplateId(templateId);
			templateSMS.setTo(to);
			templateSMS.setParam(param);
			
			Gson gson = new Gson();
			String body = gson.toJson(templateSMS);
			body="{\"templateSMS\":"+body+"}";
			
			HttpResponse response=post("application/json", timestamp, url, httpclient, encryptUtil, body);
			
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity, "UTF-8");
			}
			
			EntityUtils.consume(entity);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			// 关闭连接
		   httpclient.getConnectionManager().shutdown();
		}
		return result;
	}
	
	private HttpResponse post(String cType, 
							String timestamp, 
							String url, 
							DefaultHttpClient httpclient, 
							EncryptUtil encryptUtil, 
							String body) throws Exception{
		
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader("Accept", cType);
		httppost.setHeader("Content-Type", cType+";charset=utf-8");
		
		String src = accountSid + ":" + timestamp;
		String auth = encryptUtil.base64Encoder(src);
		httppost.setHeader("Authorization", auth);
		
		BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
        requestBody.setContentLength(body.getBytes("UTF-8").length);
        
        httppost.setEntity(requestBody);
        // 执行客户端请求
		HttpResponse response = httpclient.execute(httppost);
		
		return response;
	}
	
	private String getSignature(String timestamp, EncryptUtil encryptUtil) throws Exception{
		String sig = accountSid + authToken + timestamp;
		String signature = encryptUtil.md5Digest(sig);
		return signature;
	}
	
	private StringBuffer getStringBuffer() {
		StringBuffer sb = new StringBuffer("https://");
		sb.append(server);
		return sb;
	}
}
